{% extends "base_config.html" %}
{% block content %}

<div class="page">
    <div class="section">
        <h2 class="section-title">Plugins</h2>
        <div class="section-cards">
            <div class="card">
                <div class="card-title-row">
                    <img class="card-icon" src="/static/assets/icons/github.svg" alt="Github">
                    <h3 class="card-title">
                        Github
                        {% if current_config.content_type.github %}
                            {% if current_model_state.github == False %}
                                <img id="misconfigured-icon-github" class="configured-icon" src="/static/assets/icons/question-mark-icon.svg" alt="Not Configured" title="Embeddings have not been generated yet for this content type. Either the configuration is invalid, or you just need to click Configure.">
                            {% else %}
                                <img id="configured-icon-github" class="configured-icon" src="/static/assets/icons/confirm-icon.svg" alt="Configured">
                            {% endif %}
                        {% endif %}
                    </h3>
                </div>
                <div class="card-description-row">
                <p class="card-description">Set repositories to index</p>
                </div>
                <div class="card-action-row">
                    <a class="card-button" href="/config/content_type/github">
                        {% if current_config.content_type.github %}
                            Update
                        {% else %}
                            Setup
                        {% endif %}
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"></path></svg>
                    </a>
                </div>
                {% if current_config.content_type.github %}
                    <div id="clear-github" class="card-action-row">
                        <button class="card-button" onclick="clearContentType('github')">
                            Disable
                        </button>
                    </div>
                {% endif %}
            </div>
            <div class="card">
                <div class="card-title-row">
                    <img class="card-icon" src="/static/assets/icons/notion.svg" alt="Notion">
                    <h3 class="card-title">
                        Notion
                        {% if current_config.content_type.notion %}
                            {% if current_model_state.notion == False %}
                                <img id="misconfigured-icon-notion" class="configured-icon" src="/static/assets/icons/question-mark-icon.svg" alt="Not Configured" title="Embeddings have not been generated yet for this content type. Either the configuration is invalid, or you just need to click Configure.">
                            {% else %}
                                <img id="configured-icon-notion" class="configured-icon" src="/static/assets/icons/confirm-icon.svg" alt="Configured">
                            {% endif %}
                        {% endif %}
                    </h3>
                </div>
                <div class="card-description-row">
                    <p class="card-description">Configure your settings from Notion</p>
                </div>
                <div class="card-action-row">
                    <a class="card-button" href="/config/content_type/notion">
                        {% if current_config.content_type.content %}
                            Update
                        {% else %}
                            Setup
                        {% endif %}
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"></path></svg>
                    </a>
                </div>
                {% if current_config.content_type.notion %}
                    <div id="clear-notion" class="card-action-row">
                        <button class="card-button" onclick="clearContentType('notion')">
                            Disable
                        </button>
                    </div>
                {% endif %}
            </div>
            <div class="card">
                <div class="card-title-row">
                    <img class="card-icon" src="/static/assets/icons/markdown.svg" alt="markdown">
                    <h3 class="card-title">
                        Markdown
                        {% if current_config.content_type.markdown %}
                            {% if current_model_state.markdown == False%}
                                <img id="misconfigured-icon-markdown" class="configured-icon" src="/static/assets/icons/question-mark-icon.svg" alt="Not Configured" title="Embeddings have not been generated yet for this content type. Either the configuration is invalid, or you just need to click Configure.">
                            {% else %}
                                <img id="configured-icon-markdown" class="configured-icon" src="/static/assets/icons/confirm-icon.svg" alt="Configured">
                            {% endif %}
                        {% endif %}
                    </h3>
                </div>
                <div class="card-description-row">
                    <p class="card-description">Set markdown files to index</p>
                </div>
                <div class="card-action-row">
                    <a class="card-button" href="/config/content_type/markdown">
                        {% if current_config.content_type.markdown %}
                            Update
                        {% else %}
                            Setup
                        {% endif %}
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"></path></svg>
                    </a>
                </div>
                {% if current_config.content_type.markdown %}
                    <div id="clear-markdown" class="card-action-row">
                        <button class="card-button" onclick="clearContentType('markdown')">
                            Disable
                        </button>
                    </div>
                {% endif %}
            </div>
            <div class="card">
                <div class="card-title-row">
                    <img class="card-icon" src="/static/assets/icons/org.svg" alt="org">
                    <h3 class="card-title">
                        Org
                        {% if current_config.content_type.org %}
                            {% if current_model_state.org == False %}
                                <img id="misconfigured-icon-org" class="configured-icon" src="/static/assets/icons/question-mark-icon.svg" alt="Not Configured" title="Embeddings have not been generated yet for this content type. Either the configuration is invalid, or you just need to click Configure.">
                            {% else %}
                                <img id="configured-icon-org" class="configured-icon" src="/static/assets/icons/confirm-icon.svg" alt="Configured">
                            {% endif %}
                        {% endif %}
                    </h3>
                </div>
                <div class="card-description-row">
                <p class="card-description">Set org files to index</p>
                </div>
                <div class="card-action-row">
                    <a class="card-button" href="/config/content_type/org">
                        {% if current_config.content_type.org %}
                            Update
                        {% else %}
                            Setup
                        {% endif %}
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"></path></svg>
                    </a>
                </div>
                {% if current_config.content_type.org %}
                    <div id="clear-org" class="card-action-row">
                        <button class="card-button" onclick="clearContentType('org')">
                            Disable
                        </button>
                    </div>
                {% endif %}
            </div>
            <div class="card">
                <div class="card-title-row">
                    <img class="card-icon" src="/static/assets/icons/pdf.svg" alt="PDF">
                    <h3 class="card-title">
                        PDF
                        {% if current_config.content_type.pdf %}
                            {% if current_model_state.pdf == False %}
                                <img id="misconfigured-icon-pdf" class="configured-icon" src="/static/assets/icons/question-mark-icon.svg" alt="Not Configured" title="Embeddings have not been generated yet for this content type. Either the configuration is invalid, or you need to click Configure.">
                            {% else %}
                                <img id="configured-icon-pdf" class="configured-icon" src="/static/assets/icons/confirm-icon.svg" alt="Configured">
                            {% endif %}
                        {% endif %}
                    </h3>
                </div>
                <div class="card-description-row">
                <p class="card-description">Set PDF files to index</p>
                </div>
                <div class="card-action-row">
                    <a class="card-button" href="/config/content_type/pdf">
                        {% if current_config.content_type.pdf %}
                            Update
                        {% else %}
                            Setup
                        {% endif %}
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"></path></svg>
                    </a>
                </div>
                {% if current_config.content_type.pdf %}
                    <div id="clear-pdf" class="card-action-row">
                        <button class="card-button" onclick="clearContentType('pdf')">
                            Disable
                        </button>
                    </div>
                {% endif %}
            </div>
            <div class="card">
                <div class="card-title-row">
                    <img class="card-icon" src="/static/assets/icons/plaintext.svg" alt="Plaintext">
                    <h3 class="card-title">
                        Plaintext
                        {% if current_config.content_type.plaintext %}
                            {% if current_model_state.plaintext == False %}
                                <img id="misconfigured-icon-plaintext" class="configured-icon" src="/static/assets/icons/question-mark-icon.svg" alt="Not Configured" title="Embeddings have not been generated yet for this content type. Either the configuration is invalid, or you need to click Configure.">
                            {% else %}
                                <img id="configured-icon-plaintext" class="configured-icon" src="/static/assets/icons/confirm-icon.svg" alt="Configured">
                            {% endif %}
                        {% endif %}
                    </h3>
                </div>
                <div class="card-description-row">
                <p class="card-description">Set Plaintext files to index</p>
                </div>
                <div class="card-action-row">
                    <a class="card-button" href="/config/content_type/plaintext">
                        {% if current_config.content_type.plaintext %}
                            Update
                        {% else %}
                            Setup
                        {% endif %}
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"></path></svg>
                    </a>
                </div>
                {% if current_config.content_type.plaintext %}
                    <div id="clear-plaintext" class="card-action-row">
                        <button class="card-button" onclick="clearContentType('plaintext')">
                            Disable
                        </button>
                    </div>
                {% endif %}
            </div>
        </div>
    </div>
    <div class="section">
        <h2 class="section-title">Features</h2>
        <div class="section-cards">
            <div class="card">
                <div class="card-title-row">
                    <img class="card-icon" src="/static/assets/icons/openai-logomark.svg" alt="Chat">
                    <h3 class="card-title">
                        Chat
                        {% if current_config.processor and current_config.processor.conversation.openai %}
                            {% if current_model_state.conversation_openai == False %}
                                <img id="misconfigured-icon-conversation-processor" class="configured-icon" src="/static/assets/icons/question-mark-icon.svg" alt="Not Configured" title="The OpenAI configuration did not work as expected.">
                            {% else %}
                                <img id="configured-icon-conversation-processor" class="configured-icon" src="/static/assets/icons/confirm-icon.svg" alt="Configured">
                            {% endif %}
                        {% endif %}
                    </h3>
                </div>
                <div class="card-description-row">
                <p class="card-description">Setup chat using OpenAI</p>
                </div>
                <div class="card-action-row">
                    <a class="card-button" href="/config/processor/conversation/openai">
                        {% if current_config.processor and current_config.processor.conversation.openai %}
                            Update
                        {% else %}
                            Setup
                        {% endif %}
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"></path></svg>
                    </a>
                </div>
                {% if current_config.processor and current_config.processor.conversation.openai %}
                    <div id="clear-conversation" class="card-action-row">
                        <button class="card-button" onclick="clearConversationProcessor()">
                            Disable
                        </button>
                    </div>
                {% endif %}
            </div>
            <div class="card">
                <div class="card-title-row">
                    <img class="card-icon" src="/static/assets/icons/chat.svg" alt="Chat">
                    <h3 class="card-title">
                        Offline Chat
                        <img id="configured-icon-conversation-enable-offline-chat" class="configured-icon {% if current_config.processor and current_config.processor.conversation and current_config.processor.conversation.enable_offline_chat and current_model_state.conversation_gpt4all %}enabled{% else %}disabled{% endif %}" src="/static/assets/icons/confirm-icon.svg" alt="Configured">
                        {% if current_config.processor and current_config.processor.conversation and current_config.processor.conversation.enable_offline_chat and not current_model_state.conversation_gpt4all %}
                            <img id="misconfigured-icon-conversation-enable-offline-chat" class="configured-icon" src="/static/assets/icons/question-mark-icon.svg" alt="Not Configured" title="The model was not downloaded as expected.">
                        {% endif %}
                    </h3>
                </div>
                <div class="card-description-row">
                <p class="card-description">Setup offline chat (Llama V2)</p>
                </div>
                <div id="clear-enable-offline-chat" class="card-action-row {% if current_config.processor and current_config.processor.conversation and current_config.processor.conversation.enable_offline_chat %}enabled{% else %}disabled{% endif %}">
                    <button class="card-button" onclick="toggleEnableLocalLLLM(false)">
                        Disable
                    </button>
                </div>
                <div id="set-enable-offline-chat" class="card-action-row {% if current_config.processor and current_config.processor.conversation and current_config.processor.conversation.enable_offline_chat %}disabled{% else %}enabled{% endif %}">
                    <button class="card-button happy" onclick="toggleEnableLocalLLLM(true)">
                        Enable
                    </button>
                </div>
                <div id="toggle-enable-offline-chat" class="card-action-row disabled">
                    <div class="loader"></div>
                </div>
            </div>
        </div>
    </div>
    <div class="section">
        <div id="results-count" title="Number of items to show in search and use for chat response">
            <label for="results-count-slider">Results Count: <span id="results-count-value">5</span></label>
            <input type="range" id="results-count-slider" name="results-count-slider" min="1" max="10" step="1" value="5">
        </div>
        <div id="status" style="display: none;"></div>
    </div>
    <div class="section finalize-actions">
        <button id="configure" type="submit" title="Update index with the latest changes">⚙️ Configure</button>
        <button id="reinitialize" type="submit" title="Regenerate index from scratch">🔄 Reinitialize</button>
    </div>
</div>
<script>
    function clearContentType(content_type) {
        const csrfToken = document.cookie.split('; ').find(row => row.startsWith('csrftoken'))?.split('=')[1];
        fetch('/api/delete/config/data/content_type/' + content_type, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.status == "ok") {
                var contentTypeClearButton = document.getElementById("clear-" + content_type);
                contentTypeClearButton.style.display = "none";

                var configuredIcon = document.getElementById("configured-icon-" + content_type);
                if (configuredIcon) {
                    configuredIcon.style.display = "none";
                }

                var misconfiguredIcon = document.getElementById("misconfigured-icon-" + content_type);
                if (misconfiguredIcon) {
                    misconfiguredIcon.style.display = "none";
                }
            }
        })
    };

    function toggleEnableLocalLLLM(enable) {
        const csrfToken = document.cookie.split('; ').find(row => row.startsWith('csrftoken'))?.split('=')[1];
        var toggleEnableLocalLLLMButton = document.getElementById("toggle-enable-offline-chat");
        toggleEnableLocalLLLMButton.classList.remove("disabled");
        toggleEnableLocalLLLMButton.classList.add("enabled");

        fetch('/api/config/data/processor/conversation/enable_offline_chat' + '?enable_offline_chat=' + enable, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.status == "ok") {
                // Toggle the Enabled/Disabled UI based on the action/response.
                var enableLocalLLLMButton = document.getElementById("set-enable-offline-chat");
                var disableLocalLLLMButton = document.getElementById("clear-enable-offline-chat");
                var configuredIcon = document.getElementById("configured-icon-conversation-enable-offline-chat");
                var toggleEnableLocalLLLMButton = document.getElementById("toggle-enable-offline-chat");

                toggleEnableLocalLLLMButton.classList.remove("enabled");
                toggleEnableLocalLLLMButton.classList.add("disabled");


                if (enable) {
                    enableLocalLLLMButton.classList.add("disabled");
                    enableLocalLLLMButton.classList.remove("enabled");

                    configuredIcon.classList.add("enabled");
                    configuredIcon.classList.remove("disabled");

                    disableLocalLLLMButton.classList.remove("disabled");
                    disableLocalLLLMButton.classList.add("enabled");
                } else {
                    enableLocalLLLMButton.classList.remove("disabled");
                    enableLocalLLLMButton.classList.add("enabled");

                    configuredIcon.classList.remove("enabled");
                    configuredIcon.classList.add("disabled");

                    disableLocalLLLMButton.classList.add("disabled");
                    disableLocalLLLMButton.classList.remove("enabled");
                }

            }
        })
    }

    function clearConversationProcessor() {
        const csrfToken = document.cookie.split('; ').find(row => row.startsWith('csrftoken'))?.split('=')[1];
        fetch('/api/delete/config/data/processor/conversation/openai', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.status == "ok") {
                var conversationClearButton = document.getElementById("clear-conversation");
                conversationClearButton.style.display = "none";

                var configuredIcon = document.getElementById("configured-icon-conversation-processor");
                if (configuredIcon) {
                    configuredIcon.style.display = "none";
                }

                var misconfiguredIcon = document.getElementById("misconfigured-icon-conversation-processor");

                if (misconfiguredIcon) {
                    misconfiguredIcon.style.display = "none";
                }
            }
        })
    };

    var configure = document.getElementById("configure");
    configure.addEventListener("click", function(event) {
        event.preventDefault();
        updateIndex(
            force=false,
            successText="Configured successfully!",
            errorText="Unable to configure. Raise issue on Khoj <a href='https://github.com/khoj-ai/khoj/issues'>Github</a> or <a href='https://discord.gg/BDgyabRM6e'>Discord</a>.",
            button=configure,
            loadingText="Configuring...",
            emoji="⚙️");
    });

    var reinitialize = document.getElementById("reinitialize");
    reinitialize.addEventListener("click", function(event) {
        event.preventDefault();
        updateIndex(
            force=true,
            successText="Reinitialized successfully!",
            errorText="Unable to reinitialize. Raise issue on Khoj <a href='https://github.com/khoj-ai/khoj/issues'>Github</a> or <a href='https://discord.gg/BDgyabRM6e'>Discord</a>.",
            button=reinitialize,
            loadingText="Reinitializing...",
            emoji="🔄");
    });

    function updateIndex(force, successText, errorText, button, loadingText, emoji) {
        const csrfToken = document.cookie.split('; ').find(row => row.startsWith('csrftoken'))?.split('=')[1];
        button.disabled = true;
        button.innerHTML = emoji + " " + loadingText;
        fetch('/api/update?&client=web&force=' + force, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            }
        })
        .then(response => response.json())
        .then(data => {
            console.log('Success:', data);
            if (data.detail != null) {
                throw new Error(data.detail);
            }
            document.getElementById("status").innerHTML = emoji + " " + successText;
            document.getElementById("status").style.display = "block";
            button.disabled = false;
            button.innerHTML = '✅ Done!';
        })
        .catch((error) => {
            console.error('Error:', error);
            document.getElementById("status").innerHTML = emoji + " " + errorText
            document.getElementById("status").style.display = "block";
            button.disabled = false;
            button.innerHTML = '⚠️ Unsuccessful';
        });
    }

    // Setup the results count slider
    const resultsCountSlider = document.getElementById('results-count-slider');
    const resultsCountValue = document.getElementById('results-count-value');

    // Set the initial value of the slider
    resultsCountValue.textContent = resultsCountSlider.value;

    // Store the slider value in localStorage when it changes
    resultsCountSlider.addEventListener('input', () => {
        resultsCountValue.textContent = resultsCountSlider.value;
        localStorage.setItem('khojResultsCount', resultsCountSlider.value);
    });

    // Get the slider value from localStorage on page load
    const storedResultsCount = localStorage.getItem('khojResultsCount');
    if (storedResultsCount) {
        resultsCountSlider.value = storedResultsCount;
        resultsCountValue.textContent = storedResultsCount;
    }
</script>
{% endblock %}
